<template>
  <div class="volunteer-box">
    <div class="title">我的志愿分组</div>
    <div class="content">
      <el-empty v-if="loading" description="加载中..." />
      <el-empty v-else-if="!groupVolunteers || groupVolunteers.length === 0" description="暂无志愿信息" />

      <!-- 手风琴效果 -->
      <el-collapse v-else v-model="activeNames" accordion>
        <el-collapse-item v-for="group in groupVolunteers" :key="group.groupId" :name="group.groupId">
          <!-- 分组标题 -->
          <template #title>
            <div class="group-header">
              <div class="group-info">
                <el-tag type="primary" >{{group.grade.gradeName}}{{ group.groupName }}</el-tag>
                <el-tag type="info" size="small" style="margin-left: 8px">{{ group.volunteers?.length || 0 }} 个志愿</el-tag>
              </div>
              <div class="group-time">
                <el-icon><Clock /></el-icon>
                <span>{{ formatDateRange(group.startTime, group.endTime) }}</span>
              </div>
            </div>
          </template>

          <!-- 志愿列表 -->
          <div class="volunteer-list">
            <el-empty v-if="!group.volunteers || group.volunteers.length === 0" description="该分组暂无志愿" />

            <div v-else class="volunteer-items">
              <div v-for="(volunteer, index) in group.volunteers" :key="volunteer.teamId" class="volunteer-item" @click="handleViewTeamDetail(volunteer.team)">
                <!-- 志愿顺序标签和双选状态 -->
                <div class="volunteer-header">
                  <el-tag :type="getOrderTagType(volunteer.sort)" size="small"> {{ teamCode(volunteer.sort) }}</el-tag>
                  <el-tag :type="getMatchStatusType(volunteer.team)" size="small">
                    {{ getMatchStatusText(volunteer.team) }}
                  </el-tag>
                </div>

                <!-- 队伍信息 -->
                <div class="team-info">
                  <div class="team-name">
                   <span>毕设题目：</span>
                    <span>{{ volunteer.team?.teamName }}</span>
                  </div>
                  <!-- 队伍成员 -->
                  <div class="team-members" v-if="volunteer.team?.studentTeams?.length > 0">
                    <el-icon><UserFilled /></el-icon>
                    <span>队伍成员：</span>
                    <el-tag v-for="st in volunteer.team.studentTeams" :key="st.studentId" :type="st.isLeader === '1' ? 'warning' : 'info'" size="small" style="margin-left: 4px">
                      {{ st.student?.user?.nickName }}
                      <span v-if="st.isLeader === '1'">（队长）</span>
                    </el-tag>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>

    <!-- 队伍详情弹窗 -->
    <team-detail-dialog ref="teamDetailDialogRef" />
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { getTeacher } from '@/api/teacherVolunteer'
import { Clock, User, UserFilled } from '@element-plus/icons-vue'
import TeamDetailDialog from '@/views/team/components/TeamDetailDialog.vue'

const props = defineProps({
  teacherId: {
    type: Number,
    required: true
  }
})

const loading = ref(false)
const activeNames = ref([])
const groupVolunteers = ref([])
const teamDetailDialogRef = ref(null)

// 获取志愿数据
const fetchVolunteers = async () => {
  if (!props.teacherId) return

  loading.value = true
  try {
    const res = await getTeacher(props.teacherId)
    console.log('教师志愿原始数据:', res)

    if (res && res.data) {
      // 接口返回的数据已经是按分组组织好的
      // 每个分组对象包含分组信息和 volunteers 数组
      const groups = res.data || []

      groupVolunteers.value = groups.map((group) => ({
        groupId: group.groupId,
        groupName: group.groupName,
        startTime: group.startTime,
        endTime: group.endTime,
        teamMax: group.teamMax,
        teacherMax: group.teacherMax,
        grade: group.grade,
        volunteers: (group.volunteers || []).sort((a, b) => a.sort - b.sort)
      }))


      // 默认展开第一个有志愿的分组
      const firstGroupWithVolunteers = groupVolunteers.value.find((g) => g.volunteers.length > 0)
      if (firstGroupWithVolunteers) {
        activeNames.value = [firstGroupWithVolunteers.groupId]
      }
    }
  } catch (error) {
    console.error('获取志愿数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 格式化日期范围
const formatDateRange = (startTime, endTime) => {
  if (!startTime || !endTime) return '时间待定'

  const start = new Date(startTime).toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })
  const end = new Date(endTime).toLocaleDateString('zh-CN', {
    month: '2-digit',
    day: '2-digit'
  })

  return `${start} ~ ${end}`
}

// 根据志愿顺序返回标签类型
const getOrderTagType = (order) => {
  if (order === 1) return 'danger'
  if (order === 2) return 'warning'
  if (order === 3) return 'success'
  return 'info'
}

// 判断是否双选成功
const isMatchSuccess = (team) => {
  if (!team || !team.teamTeachers || !props.teacherId) return false

  // 查找当前教师在 teamTeachers 中的记录
  const currentTeacherRecord = team.teamTeachers.find(
    tt => tt.teacherId === props.teacherId
  )

  // 如果找到记录且 selectFlag 为 1，则双选成功
  return currentTeacherRecord && currentTeacherRecord.selectFlag === 1
}

// 获取双选状态文本
const getMatchStatusText = (team) => {
  return isMatchSuccess(team) ? '双选成功' : '待定中'
}

// 获取双选状态标签类型
const getMatchStatusType = (team) => {
  return isMatchSuccess(team) ? 'success' : 'info'
}

// 查看队伍详情
const handleViewTeamDetail = (team) => {
  if (!team) return
  teamDetailDialogRef.value?.openDialog(team, false)
}

// 监听 teacherId 变化
watch(
  () => props.teacherId,
  () => {
    if (props.teacherId) {
      fetchVolunteers()
    }
  },
  { immediate: true }
)

onMounted(() => {
  fetchVolunteers()
})
</script>

<style lang="scss" scoped>
$padding: 12px;
$border-radius: 10px;
$border-bottom: 1px solid #e5e5e5;
$full-height: calc(100dvh - 84px);
.volunteer-box {
  background-color: #fff;
  border-radius: $border-radius;
  height: 100%;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);

  .title {
    font-size: 24px;
    font-weight: 600;
    color: var(--el-color-primary);
    padding: 16px;
    border-bottom: 1px solid #e5e5e5;
    flex-shrink: 0;
  }
  .content {
    padding: 16px;
    flex: 1;
    overflow-y: auto;
    overflow-x: hidden;
  }
  :deep(.el-collapse) {
    border: none;
  }

  :deep(.el-collapse-item__header) {
    background-color: #f5f7fa;
    padding: 6px 8px;
    border-radius: 8px;
    margin-bottom: 8px;
    border: none;
    font-weight: 500;

    &:hover {
      background-color: #e6e9ee;
    }
  }

  :deep(.el-collapse-item__wrap) {
    border: none;
    background-color: transparent;
  }

  :deep(.el-collapse-item__content) {
    padding: 0 8px 8px;
  }

  .group-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;

    .group-info {
      display: flex;
      align-items: center;
    }

    .group-time {
      display: flex;
      align-items: center;
      gap: 4px;
      font-size: 12px;
      color: #909399;
    }
  }

  .volunteer-list {
    .volunteer-items {
      display: flex;
      flex-direction: column;
      gap: 12px;
    }

    .volunteer-item {
      background-color: #fff;
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      padding: 16px;
      transition: all 0.3s;
      cursor: pointer;

      &:hover {
        box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
        border-color: var(--el-color-primary);
        transform: translateY(-2px);
      }

      .volunteer-header {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 12px;
      }

      .team-info {
        .team-name {
          display: flex;
          align-items: center;
          gap: 8px;
          font-size: 16px;
          font-weight: 600;
          color: #303133;
          margin-bottom: 8px;
        }

        .team-summary {
          font-size: 14px;
          color: #606266;
          margin-bottom: 12px;
          line-height: 1.6;
        }

        .team-members {
          display: flex;
          align-items: center;
          flex-wrap: wrap;
          gap: 4px;
          font-size: 14px;
          color: #909399;

          .el-icon {
            margin-right: 4px;
          }
        }
      }
    }
  }
}
</style>
